import { DownOutlined, CloseCircleOutlined } from '@ant-design/icons';
import { App } from 'antd';
import { t } from 'i18next';
import { useState, useEffect, useMemo } from 'react';

import externalSitesService from '@/api/services/externalSitesService';
import {
  Dropdown,
  Empty,
  Search,
  Button,
  Tooltip,
  Checkbox,
  Select,
} from '@/components/eai-design';
import { SvgIcon } from '@/components/icon';
import { CircleLoading } from '@/components/loading';
import PagesHeader from '@/components/pages-header';
import { useConfirm } from '@/hooks/use-confirm';
import { useRequest2 } from '@/hooks/use-request';
import { useUserInfo } from '@/store/userStore';
import { ExternalSite, ExternalSiteGroup, ExternalSitesTag } from '@/types/nav/api';

import ImportModal from './components/ImportModal';
import SiteItem from './components/SiteItem';
import SiteModal from './components/SiteModal';

const AiNav = () => {
  const { role: userRole } = useUserInfo();
  const { message } = App.useApp();
  const [searchValue, setSearchValue] = useState('');
  const [selectedIds, setSelectedIds] = useState<string[]>([]);
  const [selectedTags, setSelectedTags] = useState<string>('全部');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isImportModalVisible, setIsImportModalVisible] = useState(false);
  const [expandedGroups, setExpandedGroups] = useState<Set<string>>(new Set());
  const [isAllSelected, setIsAllSelected] = useState(false);
  const [editSite, setEditSite] = useState<ExternalSite | undefined>(undefined);
  const [isEditMode, setIsEditMode] = useState(false);

  const importMenuItems = [
    {
      key: '1',
      label: (
        <div className="flex items-center">
          <SvgIcon icon="ic--baseline-plus" size={16} className="mr-2" />
          单个创建
        </div>
      ),
      onClick: () => {
        setIsModalVisible(true);
      },
    },
    {
      key: '2',
      label: (
        <div className="flex items-center">
          <SvgIcon icon="ic--baseline-playlist-add" size={16} className="mr-2" />
          批量导入
        </div>
      ),
      onClick: () => {
        setIsImportModalVisible(true);
      },
    },
  ];

  const {
    data: tags,
    loading: tagsLoading,
    refresh: refreshTags,
  } = useRequest2(
    async () => {
      return externalSitesService.getExternalSitesTagList();
    },
    {
      manual: false,
      refreshDeps: [isModalVisible],
      debounceWait: 300,
    },
  );

  const {
    data: externalSitesData,
    loading,
    refresh: refreshSites,
  } = useRequest2(
    async () => {
      return externalSitesService.getExternalSitesList({
        page: 1,
        page_size: 1000,
        searchText: searchValue,
        tags: selectedTags === '全部' ? '' : selectedTags,
      });
    },
    {
      manual: false,
      refreshDeps: [searchValue, selectedTags],
      debounceWait: 300,
    },
  );

  const refresh = () => {
    refreshSites();
    refreshTags();
  };

  const total = useMemo(() => {
    return externalSitesData?.total || 0;
  }, [externalSitesData]);

  const siteGroups = useMemo(() => {
    return externalSitesData?.list?.sort((a, b) => a.tag_sort_order - b.tag_sort_order) || [];
  }, [externalSitesData]);

  const tagList = useMemo(() => {
    return tags?.tags
      ? tags.tags
          .sort((a, b) => a.sort_order - b.sort_order)
          .map((tag) => ({
            label: tag.name,
            value: tag.name,
            id: tag.id,
            sort_order: tag.sort_order,
          }))
      : [];
  }, [tags]);

  const { openConfirm: openConfirmDel, ConfirmModal: ConfirmDelModal } = useConfirm({
    content: t('confirm_del_extern_site_tip', {
      name: tags?.tags
        .filter((tag) => selectedIds.includes(tag.id))
        .map((tag) => tag.name)
        .join(','),
    }),
    type: 'delete',
  });

  // 监听selectedIds变化，更新全选状态
  useEffect(() => {
    const allSiteIds = siteGroups.flatMap((group) => group.sites.map((site) => site.id));
    const isAllSelectedNow =
      allSiteIds.length > 0 && allSiteIds.every((id) => selectedIds.includes(id));
    setIsAllSelected(isAllSelectedNow);
  }, [selectedIds, siteGroups]);

  const onCheck = (id: string, isChecked: boolean) => {
    setSelectedIds((prev) => {
      if (isChecked) {
        return [...prev, id];
      }
      return prev.filter((item) => item !== id);
    });
  };

  const onCategoryCheck = (categoryTag: string, isChecked: boolean) => {
    const categorySites = siteGroups.find((group) => group.tag === categoryTag)?.sites || [];
    const siteIds = categorySites.map((site) => site.id);

    setSelectedIds((prev) => {
      if (isChecked) {
        // 添加该分类下所有site的id，去重
        const newIds = [...prev];
        siteIds.forEach((id) => {
          if (!newIds.includes(id)) {
            newIds.push(id);
          }
        });
        return newIds;
      }
      // 移除该分类下所有site的id
      return prev.filter((id) => !siteIds.includes(id));
    });
  };

  const isCategorySelected = (categoryTag: string) => {
    const categorySites = siteGroups.find((group) => group.tag === categoryTag)?.sites || [];
    const siteIds = categorySites.map((site) => site.id);
    return siteIds.length > 0 && siteIds.every((id) => selectedIds.includes(id));
  };

  const isCategoryIndeterminate = (categoryTag: string) => {
    const categorySites = siteGroups.find((group) => group.tag === categoryTag)?.sites || [];
    const siteIds = categorySites.map((site) => site.id);
    const selectedCount = siteIds.filter((id) => selectedIds.includes(id)).length;
    return selectedCount > 0 && selectedCount < siteIds.length;
  };

  const toggleExpanded = (groupId: string) => {
    setExpandedGroups((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(groupId)) {
        newSet.delete(groupId);
      } else {
        newSet.add(groupId);
      }
      return newSet;
    });
  };

  const onDelete = async (site_ids: string[]) => {
    try {
      await externalSitesService.deleteExternalSite(site_ids);
      setSelectedIds([]);
      message.success('删除成功');
      refresh();
    } catch (error) {
      console.error(error);
    }
  };

  const onDeleteConfirm = async (site_ids: string[]) => {
    // 获取site_ids对应的site名称
    const name = siteGroups
      .find((group) => group.sites.some((site) => site_ids.includes(site.id)))
      ?.sites.filter((site) => site_ids.includes(site.id))
      .map((site) => site.name)
      .join(',');

    openConfirmDel(
      () => onDelete(site_ids),
      undefined,
      t('confirm_del_extern_site_tip', {
        name,
      }),
    )();
  };

  const renderSites = (sites: ExternalSite[], groupId: string, isEditMode: boolean) => {
    const isExpanded = expandedGroups.has(groupId);
    const displaySites = isExpanded ? sites : sites.slice(0, 9);
    const hasMore = sites.length > 10;

    return (
      <div className="mt-2 grid flex-1 grid-cols-5 flex-col gap-2">
        {displaySites.map((site, index) => {
          return (
            <SiteItem
              key={index}
              site={site}
              selected={selectedIds.includes(site.id)}
              onCheck={onCheck}
              isEditMode={isEditMode}
              onEdit={() => {
                setEditSite(site);
                setIsModalVisible(true);
              }}
              onDelete={() => {
                onDeleteConfirm([site.id]);
              }}
            />
          );
        })}
        {!isExpanded && hasMore && (
          <div
            className="bg-gray-50 flex cursor-pointer items-center justify-center rounded-lg border-[1px] border-dashed border-gray-300 transition-colors hover:border-blue-400 hover:bg-blue-50"
            style={{ height: '152px' }}
            onClick={() => toggleExpanded(groupId)}
          >
            <div className="flex items-center">
              <SvgIcon icon="work-more" size={16} />
              <span className="text-sm text-gray-600">
                查看更多<span className="text-xs text-gray-400">({sites.length - 9}个)</span>
              </span>
            </div>
          </div>
        )}
      </div>
    );
  };

  const { run: updateTagSortOrders, loading: updateTagSortOrdersLoading } = useRequest2(
    async (tags: (Pick<ExternalSitesTag, 'name' | 'sort_order'> & { tag_id: string })[]) => {
      return externalSitesService.updateExternalSitesTags(tags);
    },
  );

  // 检查移动操作是否有效
  const isValidMove = (index: number, type: 'up' | 'down' | 'top'): boolean => {
    if (type === 'up' && index === 0) {
      message.warning('已经是第一个了');
      return false;
    }
    if (type === 'down' && index === siteGroups.length - 1) {
      message.warning('已经是最后一个了');
      return false;
    }
    return true;
  };

  // 处理置顶逻辑
  const handleTopOperation = async (currentTag: ExternalSiteGroup) => {
    const minSortOrder = Math.min(...tagList.map((t) => t.sort_order));
    const newSortOrder = minSortOrder - 1;
    const tag = tagList.find((t) => t.label === currentTag.tag);

    if (!tag) {
      message.warning('标签不存在');
      return;
    }

    await updateTagSortOrders([
      {
        tag_id: tag.id,
        name: tag.label,
        sort_order: newSortOrder,
      },
    ]);
  };

  // 处理上移/下移逻辑
  const handleMoveOperation = async (
    currentTag: ExternalSiteGroup,
    index: number,
    type: 'up' | 'down',
  ) => {
    const targetIndex = type === 'up' ? index - 1 : index + 1;
    const targetTag = siteGroups[targetIndex];

    if (!targetTag) return;

    const currentSortOrder = currentTag.tag_sort_order;
    const targetSortOrder = targetTag.tag_sort_order;

    const { newCurrentSortOrder, newTargetSortOrder } = calculateNewSortOrders(
      currentSortOrder,
      targetSortOrder,
      type,
    );

    const oldTag = tagList.find((t) => t.label === currentTag.tag);
    const newTag = tagList.find((t) => t.label === targetTag.tag);

    if (!oldTag || !newTag) {
      message.warning('标签不存在');
      return;
    }

    await updateTagSortOrders([
      {
        tag_id: oldTag.id,
        name: oldTag.label,
        sort_order: newCurrentSortOrder,
      },
      {
        tag_id: newTag.id,
        name: newTag.label,
        sort_order: newTargetSortOrder,
      },
    ]);
  };

  // 计算新的排序值
  const calculateNewSortOrders = (
    currentSortOrder: number,
    targetSortOrder: number,
    type: 'up' | 'down',
  ) => {
    let newCurrentSortOrder = targetSortOrder;
    let newTargetSortOrder = currentSortOrder;

    if (currentSortOrder === targetSortOrder) {
      if (type === 'up') {
        newCurrentSortOrder = targetSortOrder - 1;
        newTargetSortOrder = targetSortOrder;
      } else if (type === 'down') {
        newCurrentSortOrder = targetSortOrder;
        newTargetSortOrder = targetSortOrder + 1;
      }
    }

    return { newCurrentSortOrder, newTargetSortOrder };
  };

  const updateTagSortOrder = async (name: string, index: number, type: 'up' | 'down' | 'top') => {
    if (!isValidMove(index, type)) return;

    const currentTag = siteGroups.find((tag) => tag.tag === name);
    if (!currentTag) return;

    try {
      if (type === 'top') {
        await handleTopOperation(currentTag);
      } else {
        await handleMoveOperation(currentTag, index, type);
      }

      // 刷新数据
      refreshTags();
      refreshSites();
      message.success('排序更新成功');
    } catch (error) {
      console.error('更新排序失败:', error);
      message.error('更新排序失败');
    }
  };

  const isAdmin = useMemo(() => {
    return userRole?.code === 'super_admin';
  }, [userRole]);

  return (
    <div className="relative flex h-full flex-col overflow-hidden">
      <PagesHeader>{t('sys.menu.AINav')}</PagesHeader>
      <div className="!p-5">
        <div className="flex w-full items-center ">
          <div className=" flex items-center justify-end gap-4 rounded-lg ">
            <Select
              loading={tagsLoading}
              value={selectedTags}
              options={[{ label: '全部', value: '全部' }, ...tagList]}
              defaultValue="全部"
              showSearch
              onChange={(value) => {
                setSelectedTags(value);
              }}
              className="rg-custom-select w-[200px]"
            />
            <Search
              value={searchValue}
              onChange={(e) => {
                setSearchValue(e.target.value);
              }}
              placeholder="搜索"
            />
          </div>
          {isAdmin && (
            <div className="ml-auto flex items-center gap-4">
              {isEditMode && (
                <>
                  {selectedIds && <span>已选择{selectedIds.length}项</span>}

                  <Button
                    onClick={() => {
                      setIsEditMode(false);
                      setSelectedIds([]);
                      setIsAllSelected(false);
                    }}
                    color="default"
                    variant="outlined"
                    style={{
                      background: 'var(--fill-1)',
                      borderColor: 'var(--line-2)',
                      padding: '0 12px 0px 8px',
                    }}
                    icon={<CloseCircleOutlined />}
                  >
                    取消
                  </Button>
                  <Button
                    danger
                    onClick={() => {
                      console.log(selectedIds);
                      if (selectedIds?.length === 0) {
                        message.warning('未选择导航');
                        return;
                      }
                      onDeleteConfirm(selectedIds);
                    }}
                    style={{
                      padding: '0 12px 0px 8px',
                    }}
                    // disabled={tableSelectEdRows.length === 0}
                  >
                    <SvgIcon icon="delete-outlined" size={16} />
                    删除
                  </Button>
                </>
              )}
              {!isEditMode && (
                <Button
                  type="secondary"
                  onClick={() => {
                    setIsEditMode(!isEditMode);
                  }}
                >
                  编辑
                </Button>
              )}
              <Dropdown menu={{ items: importMenuItems }} trigger={['hover', 'click']}>
                <Button style={{ color: '#1B6DFA', border: '1px solid #1B6DFA' }}>
                  新增{t('sys.menu.AINav')}
                  <DownOutlined />
                </Button>
              </Dropdown>
            </div>
          )}
        </div>
      </div>

      {/* 筛选区域 */}
      <div className="flex flex-1 flex-col overflow-hidden pb-2 pl-5 pr-2">
        {total > 0 && isEditMode && (
          <div>
            <Checkbox
              onClick={(e) => {
                e.stopPropagation();
              }}
              onChange={() => {
                if (isAllSelected) {
                  // 取消全选
                  setSelectedIds([]);
                } else {
                  // 全选所有site
                  const allSiteIds = siteGroups.flatMap((group) =>
                    group.sites.map((site) => site.id),
                  );
                  setSelectedIds(allSiteIds);
                }
                setIsAllSelected(!isAllSelected);
              }}
              checked={isAllSelected}
            >
              <span className="text-sm font-font-weight-400 text-text-5">全选</span>
            </Checkbox>
          </div>
        )}

        {total === 0 && (
          <div className="flex h-full items-center justify-center">
            <Empty fontText="暂无数据" />
          </div>
        )}

        <div className="relative mt-2 overflow-y-auto pr-2">
          {siteGroups.map((item, index) => {
            return (
              <div key={index} className="mb-2">
                {isEditMode ? (
                  <div className="flex w-full items-center justify-between">
                    <Checkbox
                      checked={isCategorySelected(item.tag)}
                      indeterminate={isCategoryIndeterminate(item.tag)}
                      onChange={(e) => {
                        onCategoryCheck(item.tag, e.target.checked);
                      }}
                    >
                      {item.tag}
                    </Checkbox>
                    <div>
                      <Tooltip title="上移">
                        <Button
                          onClick={async () => {
                            await updateTagSortOrder(item.tag, index, 'up');
                          }}
                          type="text"
                          icon={<SvgIcon icon="up" size={16} color="var(--text-3)" />}
                        />
                      </Tooltip>
                      <Tooltip title="下移">
                        <Button
                          onClick={async () => {
                            await updateTagSortOrder(item.tag, index, 'down');
                          }}
                          type="text"
                          icon={<SvgIcon icon="down" size={16} color="var(--text-3)" />}
                        />
                      </Tooltip>
                      <Tooltip title="置顶">
                        <Button
                          onClick={async () => {
                            await updateTagSortOrder(item.tag, index, 'top');
                          }}
                          type="text"
                          icon={<SvgIcon icon="top-up" size={16} color="var(--text-3)" />}
                        />
                      </Tooltip>
                    </div>
                  </div>
                ) : (
                  <span className="text-sm font-font-weight-400 text-text-5">{item.tag}</span>
                )}
                {renderSites(item.sites, item.tag, isEditMode)}
              </div>
            );
          })}
        </div>

        {(loading || updateTagSortOrdersLoading) && (
          <div className="absolute left-0 top-0 flex h-full w-full items-center justify-center">
            <div className="flex flex-col items-center gap-2">
              <CircleLoading />
              <span className="text-sm text-text-4">
                {loading ? '导航加载中...' : '标签加载中...'}
              </span>
            </div>
          </div>
        )}
      </div>

      <SiteModal
        site={editSite}
        tags={tagList}
        open={isModalVisible}
        onCancel={() => {
          setEditSite(undefined);
          setIsModalVisible(false);
        }}
        onRefresh={refresh}
      />
      <ImportModal
        open={isImportModalVisible}
        onCancel={() => {
          setIsImportModalVisible(false);
        }}
        onRefresh={refresh}
      />
      <ConfirmDelModal />
    </div>
  );
};

export default AiNav;
